package com.bsoft.hospitalchs.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bsoft.hospitalchs.api.ApiImple;
import com.bsoft.hospitalchs.api.SimpleMyCallBack;
import com.bsoft.hospitalchs.widget.CustomProgress;

import butterknife.ButterKnife;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by 泅渡者
 * Created on 2017/3/22.
 *
 */
public abstract class BaseFragment <T extends BasePresenter> extends Fragment{
    public BaseActivity mContext;
    public View mContentView = null;
    public CustomProgress customProgress;
    /**
     * 使用CompositeSubscription来持有所有的Subscriptions
     */
    public CompositeSubscription mCompositeSubscription;
    /**
     * Api类的包装 对象
     */
    public ApiImple apiImple;

    public  T presenter;

    /**
     * 设置布局文件
     *
     * @return 返回布局文件资源Id
     */
    public abstract int onSetLayoutId();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getBaseActivity();
        customProgress = new CustomProgress(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = inflater.inflate(onSetLayoutId(), container, false);
        }
        ButterKnife.bind(this, mContentView);
        initApi();
        initView();
        return mContentView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        //解绑 presenter
        if (presenter != null) {
            presenter.unsubscribe();
        }
    }

    /**
     * 创建相应的 presenter
     */
    public void createPresenter(T presenter) {
        if (presenter != null) {
            this.presenter = presenter;
        }

    }

    public BaseActivity getBaseActivity() {
        return (BaseActivity) this.getActivity();
    }

    /**
     * 初始化 Api  更具需要初始化
     */
    public void initApi() {
        mCompositeSubscription  = mContext.getCompositeSubscription();
        apiImple = mContext.getApiImple();
    }
    public abstract void initView();

    public <T> Subscriber newMySubscriber(final SimpleMyCallBack onNext) {
        return mContext.newMySubscriber(onNext);
    }
}
